<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="java.awt.*" %>
<%@ page import="javax.imageio.ImageIO" %>
<%@ page import="java.util.Random" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/1/21
  Time: 16:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    int width = 200;
    int height = 100;

    //声明图片缓存流对象
    BufferedImage buffImg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
    //声明一个2d的画笔对象
    Graphics2D g2d = buffImg.createGraphics();

    g2d.setColor(Color.WHITE);
    g2d.fillRect(0,0,width,height);

    //设置字体
    Font font = new Font("Times New Roman",Font.BOLD,70);
    g2d.setFont(font);
    g2d.setColor(Color.BLACK);

    char cs[] = {'1','2','3','4','5','6','7','8','9',
            'a','b','c','d','e','f','g','H','I','J','K','L','M','N','Y'};

    Random r = new Random();
    StringBuffer sb = new StringBuffer();
    for(int i=0;i<4;i++){
        int index = r.nextInt(cs.length);
        sb.append(cs[index]);
    }

    //把验证码存入会话session
    session.setAttribute("code",sb.toString());

    g2d.drawString(sb.toString(),20,75);

    response.setHeader("Pragma","no-cache");
    response.setHeader("Cache-Control","no-cache");

    response.setDateHeader("Expires",0);
    response.setContentType("image/jpeg");
    ServletOutputStream sos = response.getOutputStream();
    ImageIO.write(buffImg,"jpeg",sos);

    sos.close();


%>
